namespace Roids.SL.Framework
{
    using System;
    using Microsoft.Xna.Framework;

    public static class SceneItemExtensions
    {
        public static CollisionResult CheckCollision(this SceneItem item, SceneItem candidate)
        {
            //var r1 = GetBoundsFor(item);
            //var r2 = GetBoundsFor(candidate);

            return new CollisionResult
                       {
                           HasCollided =
                               ((candidate.Position - item.Position).Length() < candidate.Radius + item.Radius),
                           CollisionPoint = item.Position
                       };
        }

        private static Rectangle GetBoundsFor(SceneItem item)
        {
            var l = Convert.ToInt16(item.Position.X - item.Radius);
            var t = Convert.ToInt16(item.Position.Y - item.Radius);
            var d = Convert.ToInt16(2*item.Radius);
            return new Rectangle(l, t, d, d);
        }

        public static void CenterIn(this SceneItem item, Rectangle bounds)
        {
            item.Position = new Vector2(
                bounds.Width/2f - item.Radius,
                bounds.Height/2f - item.Radius);
        }

        public static void WrapPositionIfCrossing(this SceneItem item, Rectangle bounds)
        {
            var w = bounds.Width + 2*item.Radius;
            var h = bounds.Height + 2*item.Radius;

            var x = item.Position.X;
            var y = item.Position.Y;

            if (x > w)
                x = -item.Radius;
            else if (x < -item.Radius)
                x = w;

            if (y > h)
                y = -item.Radius;
            else if (y < -item.Radius)
                y = h;

            item.Position = new Vector2(x, y);
        }
    }
}